How to clip shapefile features to a study area in Python


GIS in Python: Clipping Shapefile

Clipping shapefiles allows you to select certain features and attributes from a layer based on spatial extraction. For example, you may be a public health analyst interested in studying the distribution of the locations providing seasonal flu vaccinations in an area. You might seek to answer the following questions: Are there enough locations providing flu vaccinations and are they equally distributed? Where can/should a new location be added? You now have a map of the locations providing seasonal flu vaccinations throughout New York City, but suppose you are focused on Manhattan, and don’t need to see the locations in the other four boroughs. Let’s conduct this analysis using Python and the geopandas package. You can use the read_file() method from the geopandas package to read the shapefile you wish to clip and the shapefile you will use to restrict the original shapefile, then convert the coordinate reference systems of the shapefiles to an appropriate one for the geography of your data by using the to_crs() method, and then use the clip() method to clip the original spatial layer based on the other layer.


Part A: Install and Launch Jupyter Notebook via Anaconda

If you already have Anaconda downloaded and installed, you can skip Part A and directly start the analysis in Part B. Make sure you also have packages pandas, geopandas of version 0.7 or higher, matplotlib, and descartes installed in the environment where you would like to conduct this analysis. Note starting with the version 0.7, geopandas made a big change in Coordinate Reference System representation and hence some code syntax differs before and after version 0.7, as described here and here. As our tutorial writes in new version syntax, please make sure your geopandas is of version 0.7 or later in order to run the code with no error. You may check the version of geopandas and upgrade it within your environment either in Anaconda Navigator or in your terminal window.

1) First, download Anaconda. Anaconda is a free and open-source distribution of Python. You can use Anaconda to install IDEs (integrated development environments where you can write and run code) and packages like Pandas and Geopandas. Go to the link to download Anaconda, https://www.anaconda.com/products/individual, and then open the .exe file that was downloaded and follow the instructions in the installation wizard prompt.


2) Once installation is complete, open Anaconda Navigator and create a new environment for your project. A Conda environment is a directory that contains a specific collection of Conda packages that you have installed. Conda has a default environment called 'base' that includes a Python installation and some core system libraries and dependencies of Conda. It is a “best practice” to avoid installing additional packages into your base environment, and, instead, create an isolated environment to manage packages and dependencies in a new project.

Click on the Environments selection in the left sidebar menu and then click on the 'Create' at the bottom. This will open a dialog box prompting you to create a name for the new environment. You can give any name for your new environment. Here, we use 'GIS_in_Python' as the environment name. Then click the 'Create' button within the dialog box to finish the creation.


3) Once you have your project environment set up, click on the arrow to the right of your new environment, 'GIS_in_Python' in this example, and select Open Terminal. This will give you access to the command line interface on your computer in a window.


4) Install the packages/libraries necessary for the analysis by entering the following commands in the opened terminal, one line at a time:
conda install pandas
conda install geopandas
conda install matplotlib
conda install descartes


5) Once you have those libraries all installed, select the new environment, 'GIS_in_Python' in this example, in the 'Applications on' dropdown menu, and then click "install" and "launch" under Jupyter Notebook. Jupyter Notebook will open in your web browser (it does not require the internet to work).


6) In Jupyter Notebook, navigate to the folder where you saved the code file you plan to use and open the .ipynb file (the extension for Jupyter Notebook files written in Python) to run it in the Notebook. If you would like to create a new .ipynb file, browse to the folder in which you would like to save your Notebook, then click the "New" dropdown button on the top-right and select "Python 3". Your new Notebook will open in a new tab in your browser. If you want to create a new directory using the Jupyter Notebook dashboard, click the "New" dropdown button and then select "Folder". To add files from your local machine, click the "Upload" button on the top-right to open a file chooser window and then choose the file you wish to upload.


Part B: Read Data File and Perform Clipping

1) Import necessary packages/libraries.

2) Use the gpd.read_file() function from the geopandas package to read the shapefile. Optionally, you can use the head() method to return the first 5 rows of the GeoDataFrame, and use the .shape attribute to check the number of rows and columns of the GeoDataFrame in the returned tuple (number of rows, number of columns). For this example, the number of rows of the 'NYC_flu_vaccinations' and the 'Manhattan_tracts' suggest that there are 885 locations providing seasonal flu vaccinations in NYC and 288 census tracts in Manhattan.

Let’s look at the shape of the shapefiles for 'NYC_flu_vaccinations' and 'Manhattan_tracts'.

You may also use matplotlib for plotting to generate an overview of your GeoDataFrame.


3) Before clipping, use the .crs attribute to check the current Coordinate Reference System (CRS)/projection of your spatial datasets, and if they are not projected into the same coordinate reference system, use the to_crs() method to re-project the data to a projection appropriate for the geographical area of your data. This is because the geopandas package can only carry out a clipping between layers that are in the same projected coordinate.

In this example, 'NYC_flu_vaccinations' and 'Manhattan_tracts' are the two GeoDataFrame that we need to examine their projections (.crs). Since the CRS of the two GeoDataFrames are different, EPSG:4326 for the 'NYC_flu_vaccinations' and EPSG:4269 for the 'Manhattan_tracts', we must convert the CRS. A bit of research suggests that EPSG:2263 would be an appropriate projection for New York. Therefore, we convert the CRS of 'NYC_flu_vaccinations' and 'Manhattan_tracts' to EPSG:2263 (.to_crs('epsg:2263')).

For more information and resources on coordinate systems and map projections, please see Appendix 1 in NYU Data Services’ QGIS tutorial, which is available here.

4) Once the two GeoDataFrames have been converted into the same coordinate reference system, you can use the clip() method to clip the data to the boundary of the polygon layer that you select.

Optionally, by checking the .shape attribute of the new GeoDataFrame 'flu_vaccinations_clipped', the number of rows suggests that there are 315 locations providing seasonal flu vaccinations in Manhattan.

5) Now you can generate a map with the clipped spatial object overlaying the object you use for clipping. Based on the map of 'Manhattan_tracts' we generated in Step 2, add the clipped flu vaccination location point layer, 'flu_vaccinations_clipped', on the same axes (ax=ax) with black color (color="black"). You will see only clipped features remain and you can now only study the area of your interest.